package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository  //此注解一般用于描述数据逻辑层的具体实现对象,此对象要交给spring管理
public class DefaultGoodsDao implements GoodsDao{
    @Autowired
    private DataSource dataSource;
    /**
     * 对于如下如下方法的实现,你觉得?
     * 1)哪些地方比较固定
     * 2)哪些地方写的比较死板,不够灵活
     * @return
     */
    @Override
    public List<Map<String, Object>> findGoods() {
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        String sql = "select * from tb_goods";
        //1,获取jdbc连接
        try {
            connection = dataSource.getConnection();
            //2，创建Starement对象，基于此对象发送SQL
            statement = connection.createStatement();
            //3,发送SQL,执行查询
            rs = statement.executeQuery(sql);
            //4，处理结果集(将所有记录封装到List<Map<String,Object>)
            List<Map<String, Object>> list = new ArrayList<>();
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            while (rs.next()) {//循环一次,取一行,一行记录映射为一个map
//                Map<String, Object> map = new HashMap<>();
//                map.put("id", rs.getInt("id"));
//                map.put("name", rs.getString("name"));
//                map.put("remark", rs.getString("remark"));
//                map.put("createdTime", rs.getTimestamp("createdTime"));
//                list.add(map);
                list.add(rowMap(resultSetMetaData, rs));
            }
            return list;

        } catch (SQLException e) {//SQLException是一种检查异常
            e.printStackTrace();
            //return null;
            throw new RuntimeException(e);//非检查异常,这样方法就不需要声明抛出了
        } finally {
            //5，释放资源
            if (rs != null) try { rs.close(); } catch (SQLException e) { }
            if (statement != null) try { statement.close(); } catch (SQLException e) { }
            if (connection != null) try { connection.close(); } catch (SQLException e) { }
        }
    }

    //行映射
        public Map<String, Object> rowMap(ResultSetMetaData resultSetMetaData, ResultSet rs)
                throws  SQLException{
            Map<String, Object> map = new HashMap<>();
            //获取列的数量
            int columnCount = resultSetMetaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {//此循环执行结束表示一行记录映射结束
                //获取列别名,没有起别名就是列的名字
                String columnName = resultSetMetaData.getColumnLabel(i);
                //将列的名字作为key,列的值作为value存储到map集合
                map.put(columnName, rs.getObject(columnName));
            }
            return map;
    }
}
